package com.lhb.service.Impl;

import com.lhb.dao.Repository.UserRepository;
import com.lhb.dao.UserDao;
import com.lhb.dao.UserMapper;
import com.lhb.pojo.BaseResp;
import com.lhb.pojo.TbRoleVo;
import com.lhb.pojo.User;
import com.lhb.pojo.rep.TbRoleReq;
import com.lhb.pojo.rep.UserReq;
import com.lhb.pojo.rep.UserRoleReq;
import com.lhb.pojo.resp.TbRoleResp;
import com.lhb.service.UserService;
import com.lhb.utils.Md5Utils;
import javafx.scene.control.Label;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.10.11 下午 19:44
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    UserDao userDao;

    @Autowired
    UserMapper userMapper;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public BaseResp findAll(Integer page, Integer limit) {
        PageRequest of = PageRequest.of(page - 1, limit);
        Page<User> all = userRepository.findAll(of);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(0);
        baseResp.setMsg("success");
        baseResp.setCount(all.getTotalElements());
        baseResp.setData(all.getContent());
        return baseResp;
    }

    @Override
    public void deleteById(Integer id) {
        userRepository.deleteById(id);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(1);
        baseResp.setMsg("删除成功");
    }

    @Override
    public BaseResp login(UserReq userReq, HttpServletRequest request) {
        //判断验证码是否正确
        HttpSession session = request.getSession();
        Object kaptcha = session.getAttribute("kaptcha");
        if (kaptcha == null || !kaptcha.equals(userReq.getCode())) {
            return new BaseResp(1, "验证码输入错误", null, null);
        }
        /*//判断用户是否存在
        User byUserName = userRepository.findByUserName(userReq.getUserName());
        if(byUserName == null){
            return new BaseResp(1,"没有该用户,请不要尝试暴力登入",null,null);
        }
        //判断密码
        if(!byUserName.getUserPassword().equals(userReq.getUserPassword())){
            return  new BaseResp(1,"密码输入错误",null,null);
        }*/
        //使用shiro完成登录逻辑
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userReq.getUserName(), userReq.getUserPassword());
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException exception) {
            return new BaseResp(1, "密码输入错误！", null, null);
        } catch (UnknownAccountException exception) {
            return new BaseResp(1, "没有该用户，请联系管理员！", null, null);
        }
        if (subject.isAuthenticated()) {
            //从主体中获取到登录的用户名存储在session中
            String principal = (String) subject.getPrincipal();
            session.setAttribute("user", principal);
        }
        return new BaseResp(0, "登录成功,2秒后跳转首页", null, null);
    }


    @Override
    public BaseResp sendMail(Object userName, HttpSession session) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        try {
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(userName.toString());
            mimeMessageHelper.setSubject("在线教育验证码");
            //定义字符串
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < 6; i++) {
                int i1 = new Random().nextInt(10);
                stringBuffer.append(i1);
            }
            //将邮箱验证码放在session中
            session.setAttribute(userName.toString(), stringBuffer.toString());
            mimeMessageHelper.setText("<font style='color:black'>验证码为:" + stringBuffer.toString() + "</font>", true);
            javaMailSender.send(mimeMessage);
            return new BaseResp(0, "发送成功！", null, null);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return new BaseResp(1, "发送失败！", null, null);
    }

    @Override
    public BaseResp updateUser(User user) {
        int i = userDao.updateUser(user);
        BaseResp baseResp = new BaseResp();
        baseResp.setCode(0);
        baseResp.setMsg("修改成功");
        return baseResp;
    }


    @Override
    public BaseResp insertUser(UserReq userReq, HttpSession session) {
        //判断邮箱验证码
        String emailCode = userReq.getEmailCode();
        Object attribute = session.getAttribute(userReq.getUserName());
        BaseResp baseResp = new BaseResp();
        if (!emailCode.equals(attribute)) {
            baseResp.setCode(1);
            baseResp.setMsg("验证码输入错误");
            return baseResp;
        }
        //判断用户名是否存在
        User byUserName = userRepository.findByUserName(userReq.getUserName());
        if (byUserName != null) {
            baseResp.setCode(1);
            baseResp.setMsg("用户存在,请重新注册");
            return baseResp;
        }
        //添加到数据库
        Date date = new Date();
        User user = new User();
        user.setCreateTime(date);
        BeanUtils.copyProperties(userReq, user);
        Md5Utils md5Utils = new Md5Utils();
        String password = md5Utils.md5Salt(user.getUserPassword(), user.getUserName());
        user.setUserPassword(password);
        userRepository.save(user);
        //移除掉session
        session.removeAttribute(userReq.getUserName());
        baseResp.setCode(0);
        baseResp.setMsg("注册成功");
        return baseResp;
    }

    @Override
    @Transactional
    public BaseResp updateRole(UserRoleReq req) {
        //删除中间表与角色和用户的关联关系
        userMapper.delteByUserId(req.getUserid());

        //建立新的逻辑关系
        List<TbRoleReq> rollist = req.getRollist();

        TbRoleReq tbRoleReq = null;

        if (rollist != null && rollist.size() > 0) {
            tbRoleReq = rollist.get(0);
        }

        TbRoleReq tr = new TbRoleReq();
        tr.setUserid(req.getUserid());

        if (rollist != null && rollist.size() > 0) {
            tr.setRoleid(tbRoleReq.getId());
        } else {
            tr.setRoleid(3);
        }

       /* for (TbRoleReq tr : perlist){
            TbRoleVo tbRoleVo = new TbRoleVo();
            tbRoleVo.setRoleid(tr.getId());
            tbRoleVo.setUserid(req.getUserid());
            list.add(tbRoleVo);
        }*/
        userMapper.Saveall(tr);

        return new BaseResp(0, "角色赋予完毕!", null, null);
    }
}
